package com.wsz.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsz.pojo.R;
import com.wsz.pojo.UserFromDo;
import com.wsz.pojo.UserInfo;
import com.wsz.user.service.UserInfoService;
import com.wsz.user.mapper.UserInfoMapper;
import com.wsz.utils.SecurityContextUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author wangs
* @description 针对表【user_info】的数据库操作Service实现
* @createDate 2023-01-23 17:31:11
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{


    @Override
    public R updateUserFromDo(UserFromDo userFromDo) {
        String id = SecurityContextUtils.getUserId();

        Integer age = userFromDo.getAge();
        String brief = userFromDo.getBrief();
        String email = userFromDo.getEmail();
        UserInfo userInfo = new UserInfo();

        Boolean flag = false;

        if(StringUtils.isNotBlank(email)){
            userInfo.setEmail(email);
            flag = true;
        }

        if(StringUtils.isNotBlank(brief)){
            userInfo.setBrief(brief);
            flag = true;
        }

        if(age != null){
            userInfo.setAge(age);
            flag = true;
        }

        if(!flag) return R.error().message("信息为空");

        userInfo.setId(id);

        boolean b = this.updateById(userInfo);

        if(b) return R.ok();
        return R.error().message("修改失败稍后再试");
    }

    @Override
    public R updateAvatar(String avatar) {
        String userId = SecurityContextUtils.getUserId();

        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setPhoto(avatar);

        boolean b = this.updateById(userInfo);

        if(b) return R.ok();
        return  R.error().message("上传头像失败");
    }

    @Override
    public R getRanks(Long page, Long limit) {
        IPage<UserInfo> userInfoIPage = new Page<>(page,limit);

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("ranting");

        baseMapper.selectPage(userInfoIPage,queryWrapper);


        List<UserInfo> records = userInfoIPage.getRecords();
        //当前页
        long current = userInfoIPage.getCurrent();
        //总记录数
        long total = userInfoIPage.getTotal();

        return R.ok().data("current",current).data("total",total).data("records",records);
    }

}




